import { Card, Breadcrumb, Form, Select, Button, Input, Space, Radio, Upload, message } from 'antd'

import { Link } from 'react-router-dom'
import styles from "./index.module.scss";
import { useChannels } from '@/utils/customHooks';
import { useState } from 'react';
import { PlusOutlined } from '@ant-design/icons'
import ReactQuill from "react-quill"
import "react-quill/dist/quill.snow.css"
import { useDispatch } from 'react-redux';
import { addArticle, editArticle, getArticle } from '@/store/actions/article';
import { useHistory, useParams } from 'react-router-dom/cjs/react-router-dom.min';
import { useEffect } from 'react';


const Publish = () => {
    const params = useParams()
    const [form] = Form.useForm()
    // 频道数据
    const channels = useChannels()
    const [type, setType] = useState(1)
    const [fileList, setFileList] = useState([]);
    const history = useHistory()
    const dispatch = useDispatch()
    // console.log(fileList)
    // console.log(type)
    // 封面类型发生变化
    const onChangeValue = (e) => {
        setType(e.target.value);
        setFileList([])
    }

    // 表单提交
    const onFinish = async (values, draft) => {
        if (type !== fileList.length) {
            return message.warning('请按照选择的封面类型上传图片')
        }
        const data = {
            ...values,
            cover: {
                type,
                images: fileList.map(item => item?.response?.data.url || item.url)
            }
        }
        if (params.id) {
            data.id = params.id
            await dispatch(editArticle(data, draft))
        } else {
            await dispatch(addArticle(data, draft))
        }
        message.success('保存成功')
        history.push("/home/article")
    }
    // 点击存入草稿
    const saveDarft = async () => {
        try {
            const values = await form.validateFields()
            onFinish(values, true)
        } catch (error) {
            console.log(error)
            message.error('提交失败,请稍后重试')
        }
    }
    useEffect(() => {
        const getArticleInfo = async () => {
            if (params.id) {
                const { data } = await dispatch(getArticle(params.id))
                console.log(data);
                form.setFieldsValue({
                    title: data.title,
                    channel_id: data.channel_id,
                    content: data.content
                })
                setType(data.cover.type);
                setFileList(data.cover.images.map((item) => ({ url: item })));
            } else {
                setType(1);
                setFileList([]);
                form.resetFields()
            }
        }
        getArticleInfo()
    }, [params, dispatch, form])

    return (
        <div className={styles.root}>
            <Card
                title={
                    <Breadcrumb>
                        <Breadcrumb.Item>
                            <Link to="/">首页</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            <Link to="/article">内容管理</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>{params.id ? '修改文章' : '发布文章'}</Breadcrumb.Item>
                    </Breadcrumb>
                }
            >
                <Form labelCol={{ span: 4 }} onFinish={onFinish} form={form}>
                    <Form.Item
                        label="文章标题："
                        name="title"
                        rules={[{ required: true, message: "请输入文章标题" }]}
                    >
                        <Input placeholder="请输入文章标题" style={{ width: 400 }} />
                    </Form.Item>
                    <Form.Item
                        label="所属频道："
                        name="channel_id"
                        rules={[{ required: true, message: "请选择所属频道" }]}
                    >
                        <Select style={{ width: 400 }}>
                            {channels.map((item) => {
                                return (
                                    <Select.Option key={item.id} value={item.id}>
                                        {item.name}
                                    </Select.Option>
                                );
                            })}
                        </Select>
                    </Form.Item>
                    <Form.Item label="封面">
                        <Radio.Group value={type} onChange={onChangeValue}>
                            <Radio value={1}>单图</Radio>
                            <Radio value={3}>三图</Radio>
                            <Radio value={0}>无图</Radio>
                        </Radio.Group>
                        {
                            (type === 1 || type === 3) && <div style={{ marginTop: 16 }}>
                                <Upload
                                    name="image"
                                    listType="picture-card"
                                    action="http://toutiao.itheima.net/v1_0/upload"
                                    fileList={fileList}
                                    onPreview={() => { }}
                                    onChange={({ fileList }) => {
                                        setFileList(fileList)
                                    }}
                                >
                                    {fileList.length < type ? (
                                        <div>
                                            <PlusOutlined />
                                            <div style={{ marginTop: 8 }}>上传图片</div>
                                        </div>
                                    ) : null}
                                </Upload>
                            </div>
                        }
                    </Form.Item>
                    <Form.Item name="content" initialValue="" label="文章内容：" rules={[{ required: true, message: "请输入文章内容" }]}>
                        <ReactQuill placeholder="请输入文章内容"></ReactQuill>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Space>
                            <Button size='large' type="primary" htmlType='submit'>发表文章</Button>
                            <Button size='large' onClick={saveDarft}>存入草稿</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    )
}

export default Publish